package com.fyakm.javaprojectanalysis.common.util;

import com.fyakm.javaprojectanalysis.common.base.F_Class;
import com.fyakm.javaprojectanalysis.common.base.F_Package;
import org.xmind.core.*;

import java.io.IOException;
import java.util.List;

/***
 * Xmind工具类
 */
public class XmindUtil {

    /**
     * 根据F_Package生成Xmind方法
     *
     * @param f_package         解析出来的包
     * @param generatorFileName 生成的文件名
     * @param displayClass 是否显示子类
     */
    public static void generatorXmind(F_Package f_package, String generatorFileName,boolean displayClass) {
        IWorkbookBuilder builder = Core.getWorkbookBuilder();
        IWorkbook workbook = builder.createWorkbook(generatorFileName);
        ISheet sheet = workbook.getPrimarySheet();
        sheet.setTitleText(f_package.getPackageName());
        ITopic rootTopic = sheet.getRootTopic();
        rootTopic.setTitleText(f_package.getName());
        recursionGenerator(f_package, rootTopic, workbook,displayClass);
        try {
            workbook.save(generatorFileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (CoreException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 递归生成子包中的包列表和类列表
     *
     * @param f_package 父包
     * @param parent    父节点
     * @param workbook  文档
     * @param displayClass  是否显示类
     */
    private static void recursionGenerator(F_Package f_package, ITopic parent, IWorkbook workbook,boolean displayClass) {

        List<F_Package> childrenPackageList = f_package.getPackageList();
        // 添加包进去
        if (null != childrenPackageList && !childrenPackageList.isEmpty()) {
            for (F_Package childPackage : childrenPackageList) {
                ITopic child = workbook.createTopic();
                child.setStyleId("packageStyle");
                child.setTitleText(childPackage.getName());
                child.setFolded(true);  // 关闭子项
                parent.add(child);

                recursionGenerator(childPackage, child, workbook,displayClass);
            }
        }

        // 添加是否显示子类的判断，大型项目如果显示子类的话xmind会很乱
        if(displayClass){
            List<F_Class> classList = f_package.getClassList();
            // 添加类进去
            if (null != classList && !classList.isEmpty()) {
                for (F_Class fClass : classList) {
                    ITopic child = workbook.createTopic();
                    child.setTitleText(fClass.getName());
                    child.setFolded(true);
                    parent.add(child);
                }
            }
        }

    }

}
